package com.fudan.gamestore.controller;

import com.fudan.gamestore.pojo.Game;
import com.fudan.gamestore.pojo.Response;
import com.fudan.gamestore.service.GameService;
import com.fudan.gamestore.service.TokenService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class GameController {

    @Autowired
    private GameService gameService;

    @Autowired
    private TokenService tokenService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    @ResponseBody
    public List<Game> getAllGame() {
        return gameService.getAllGame();
    }

    @RequestMapping(value = "/allGames", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getAllGameByPage(@RequestParam(name = "size") Integer size,
                                                @RequestParam(name = "current") Integer current) {
        PageInfo<Game> page = gameService.getAllGameByPage(size, current);
        Map<String, Object> retMap = new HashMap<>();
        if(page != null){
            retMap.put("gameList", page.getList());
            retMap.put("total", page.getTotal());
            retMap.put("current", current);
            retMap.put("status", 200);
        }
        return retMap;
    }

    @RequestMapping(value = "/game/{gameId}", method = RequestMethod.GET)
    @ResponseBody
    public Game getGameById(@PathVariable("gameId") Integer gameId) {
        return gameService.getGameById(gameId);
    }

    @RequestMapping(value = "/game/add", method = RequestMethod.POST)
    @ResponseBody
    public Response addGame(@RequestParam String gameName, @RequestParam Double price,
                            @RequestParam String description,
                            @RequestParam(name = "saleCount", defaultValue = "0") Integer saleCount,
                            @RequestParam String gameType, @RequestParam List<String> fileUrlList,
                            @RequestHeader String token) {
        if(tokenService.checkToken(token, -1, 1) < 0){
            return new Response(400, "未授权");
        }

        Game game = new Game(null, gameName, price, fileUrlList.get(0), description, saleCount, null, gameType);

        fileUrlList.remove(0);  // 除去第一张的缩略图
        game.setDetailGameImg(fileUrlList);

        if (gameService.addGame(game) == 0) {
            return new Response(400, "failed to add game");
        } else {
            return new Response(200, "add game successfully");
        }
    }

    @RequestMapping(value = "/game/delete/{gameId}", method = RequestMethod.POST)
    @ResponseBody
    public Response deleteGame(@PathVariable("gameId") Integer gameId, HttpSession session, @RequestHeader String token) {
        if(tokenService.checkToken(token, -1, 1) < 0){
            return new Response(400, "未授权");
        }
        Game game = gameService.getGameById(gameId);
        File file;
        String finalPath;

        // 获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        // 获取当前工程下photo目录的真实路径
        String imagePath = servletContext.getRealPath("static/images/");

        // 删除图片
        String fileName = game.getGameImg();
        finalPath = imagePath + File.separator + fileName;
        file = new File(finalPath);
        file.delete();
        List<String> detailGameImg = game.getDetailGameImg();
        for (String detailFileName : detailGameImg) {
            finalPath = imagePath + File.separator + detailFileName;
            file = new File(finalPath);
            file.delete();
        }

        if (gameService.deleteGame(gameId) != 0) {
            return new Response(200, "success");
        } else {
            return new Response(400, "failed to delete game");
        }
    }

    @RequestMapping(value = "/game/owngame/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getOwnGameByUserIdPage(@PathVariable("userId") Integer userId,
                                                @RequestParam(name = "size") Integer size,
                                                @RequestParam(name = "current") Integer current,
                                                @RequestHeader String token) {
        Map<String, Object> retMap = new HashMap<>();
        if(tokenService.checkToken(token, userId, 0) < 0){
            retMap.put("status", 400);
            retMap.put("info", "未授权");
            return retMap;
        }
        PageInfo<Game> gamePageInfo = gameService.getOwnGameByUserIdPage(userId, size, current);
        if (gamePageInfo != null) {
            retMap.put("total", gamePageInfo.getTotal());
            retMap.put("current", current);
            retMap.put("gameList", gamePageInfo.getList());
            retMap.put("status", 200);
            retMap.put("info", "success");
        }
        return retMap;
    }

    @RequestMapping(value = "/game/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modifyGame(@RequestBody Game game, @RequestHeader String token) {
        if(tokenService.checkToken(token, -1, 1) < 0){
            return new Response(400, "未授权");
        }
        if (gameService.modifyGame(game) != 0) {
            return new Response(200, "success");
        } else {
            return new Response(400, "failed to modify game");
        }
    }
}
